<?php

namespace EthanZ\LaravelExt\Middleware;

use EthanZ\LaravelExt\Constants\CommonSetting;
use EthanZ\LaravelExt\Exceptions\NormalException;
use EthanZ\LaravelExt\Utils\Tools\ManufactureTools;
use EthanZ\LaravelExt\Utils\User;
use Closure;
use Illuminate\Http\Request;

/**
 * 用户登录验证
 */
class UserLoginCheck
{


    /**
     * 响应前操作.
     *
     * @param Request $request 参数.
     * @param Closure $next    继续执行.
     *
     * @return mixed
     * @throws NormalException.
     */
    public function handle(Request $request, Closure $next): mixed
    {
        $tokenData = User::userTokenData();
        if (!$tokenData) {
            throw new NormalException('USR_LOG_002');
        }

        // 验证时效.
        if ((time() - $tokenData['login_time']) > CommonSetting::USER_TOKEN_TIME_OUT) {
            throw new NormalException('USR_LOG_003');
        }

        // 登录ip验证.
        if (ManufactureTools::getIp(2) !== $tokenData['login_ip']) {
            throw new NormalException('USR_LOG_009');
        }

        // 获取用户信息.
        $userInfo = User::userInfo();
        if (!$userInfo) {
            throw new NormalException('USR_LOG_004');
        }

        // 单点登录验证.
//        if ($userInfo['last_token'] != request()->header('U-Token')) {
//            throw new NormalException('USR_LOG_005');
//        }

        // 将id放入参数.
        request()?->offsetSet('user_id', $userInfo['id']);

        return $next($request);
    }
}
